/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dtd.gui;

import com.dtd.implementation.Analyzer;
import com.dtd.implementation.CategoryTableModel;
import com.dtd.implementation.Connector;
import com.dtd.structure.IConnector;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import org.jdesktop.xswingx.PromptSupport;
import org.jsoup.Connection.Response;

/**
 *
 * @author TQD
 */
public class CategoryForm extends javax.swing.JFrame {
    //private static Map<String, String> mapCourse = null;

    private static Analyzer analyzer = null;
    private static Map<String, ArrayList> mapCategory = null;
    private static Map<String, String> mapCourse = null;
    private static Map<String, String> cookies = null;
    private String idCourse = null;
    private static CategoryTableModel model = null;

    /**
     * Creates new form CategoryForm
     */
    public CategoryForm() {
        initComponents();
        this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        this.setLocationRelativeTo(null);
        initLabelAndDefaultCbx();
        initComboBox();
        initCourse();
        alignHeader(jTable1);

        jTable1.changeSelection(0, 0, false, false); //Alway have a cloumn is selected in first time loading
        PromptSupport.setPrompt("SEARCH", txtSearch);
        
    }

    /**
     * Custome method.
     */
    /**
     * This method is used for load Element to combobox
     *
     * @param none
     */
    public String getIdCourse() {
        return idCourse;
    }

    public static Map<String, String> getCookies() {
        return cookies;
    }

    private void initComboBox() {

        mapCategory = analyzer.analyzeCategory(cookies);
        Set<String> categoryName = mapCategory.keySet();

        for (String s : categoryName) {
            jComboBox1.addItem(s);
        }
    }

    /**
     * This method for small element such as: student name label and set defaul
     * value combobox
     */
    private void initLabelAndDefaultCbx() {
        cookies = LoginForm.getCookies();
        model = new CategoryTableModel();
        analyzer = new Analyzer();
        jComboBox1.addItem("__ALL CATEGORY__");
        lbName.setText(analyzer.getStudentName(cookies));

    }

    /**
     * Load all course to table
     *
     * @param table
     */
    private void initCourse() {
        String current = jComboBox1.getSelectedItem().toString();
        mapCourse = analyzer.getMapCourse();
        if (current.equals("__ALL CATEGORY__")) {
            Set<String> listCourse = mapCourse.keySet();
            jTable1.setModel(model);
            for (String s : listCourse) {
                model.getData().add(s);
            }
        } else {
            model.getData().clear();
            ArrayList<String> conditionList = mapCategory.get(current);
            for (String course : conditionList) {
                model.getData().add(course);
            }
        }

        jTable1.updateUI();

    }

    private void alignHeader(JTable table) {
        DefaultTableCellRenderer rendererHeader = (DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer();
        rendererHeader.setHorizontalAlignment(JLabel.CENTER);
        DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
        rightRenderer.setHorizontalAlignment(JLabel.CENTER);
        table.getColumnModel().getColumn(0).setCellRenderer(rightRenderer);
        ((JLabel) jComboBox1.getRenderer()).setHorizontalAlignment(0);
    }

    private void showCourseDetailsForm() {
        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        int rowIndex = jTable1.getSelectedRow();
        String course = jTable1.getValueAt(rowIndex, 0).toString();
        idCourse = mapCourse.get(course);
        IConnector connector = new Connector();
        Response response = connector.getResponseForCourse(cookies, idCourse);

        if (response.url().toString().contains("http://cms-hcm.fpt.edu.vn/elearning/course/enrol")) {
            this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
            JOptionPane.showMessageDialog(this, "Sorry, you did not enroll in this course!!!");
        } else {

            CourseDetailForm courseDetailForm = new CourseDetailForm(this, true);
            courseDetailForm.setVisible(true);
        }
    }

    private void search() {
        if (!"SEARCH".equals(txtSearch.getText().trim()) && !"".equals(txtSearch.getText().trim())) {
            String keyword = txtSearch.getText().toLowerCase();
            model.getData().clear();
            Set<String> courses = mapCourse.keySet();
            for(String s : courses){
                if(s.toLowerCase().contains(keyword)){
                    model.getData().add(s);
                }
            }
            jTable1.updateUI();
        }else{
            initCourse();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lbLogout = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        lbName = new javax.swing.JLabel();
        txtSearch = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lbLogout.setFont(new java.awt.Font("Trebuchet MS", 2, 16)); // NOI18N
        lbLogout.setText("(Logout)");
        lbLogout.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        lbLogout.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lbLogoutMouseClicked(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                lbLogoutMouseExited(evt);
            }
        });
        lbLogout.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                lbLogoutMouseMoved(evt);
            }
        });
        lbLogout.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                lbLogoutFocusLost(evt);
            }
        });

        jComboBox1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jTable1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jTable1.setForeground(new java.awt.Color(51, 51, 51));
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jTable1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jTable1.setGridColor(new java.awt.Color(153, 153, 255));
        jTable1.setRowHeight(20);
        jTable1.setSelectionBackground(new java.awt.Color(255, 255, 255));
        jTable1.setSelectionForeground(new java.awt.Color(0, 153, 204));
        jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jButton1.setText("SHOW DETAIL");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        lbName.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
        lbName.setForeground(new java.awt.Color(0, 0, 255));

        txtSearch.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtSearch.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtSearch.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                txtSearchCaretUpdate(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(29, 29, 29)
                        .addComponent(lbName, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(23, 23, 23)
                        .addComponent(lbLogout, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(30, 30, 30)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(30, 30, 30)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(29, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(108, 108, 108))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(txtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(81, 81, 81))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbName, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbLogout, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(23, 23, 23)
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(25, 25, 25)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 231, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(txtSearch, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        // TODO add your handling code here:
        initCourse();
        txtSearch.setText("");
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void lbLogoutMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbLogoutMouseMoved
        // TODO add your handling code here:
        lbLogout.setForeground(Color.BLUE);

    }//GEN-LAST:event_lbLogoutMouseMoved

    private void lbLogoutFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_lbLogoutFocusLost
    }//GEN-LAST:event_lbLogoutFocusLost

    private void lbLogoutMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbLogoutMouseExited
        // TODO add your handling code here:
        lbLogout.setForeground(Color.BLACK);
    }//GEN-LAST:event_lbLogoutMouseExited

    private void lbLogoutMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbLogoutMouseClicked
        // TODO add your handling code here:
        LoginForm.getInstance().dispose();
        LoginForm.getInstance().setVisible(true);
        this.dispose();
    }//GEN-LAST:event_lbLogoutMouseClicked

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        showCourseDetailsForm();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        // TODO add your handling code here:

        if (evt.getClickCount() == 2) {
            this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            showCourseDetailsForm();
        }
    }//GEN-LAST:event_jTable1MouseClicked

    private void txtSearchCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_txtSearchCaretUpdate
        // TODO add your handling code here:
        search();
    }//GEN-LAST:event_txtSearchCaretUpdate

    public void mouseClicked(MouseEvent evt) {
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CategoryForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CategoryForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CategoryForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CategoryForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CategoryForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JLabel lbLogout;
    private javax.swing.JLabel lbName;
    private javax.swing.JTextField txtSearch;
    // End of variables declaration//GEN-END:variables
}
